#include <MsTimer2.h>
#include "U8glib.h"


int  leftHour = -1;
int leftMinute = -1;
int leftSecond = -1;
int controllPin = 13;
char isTimeOut = 0;

U8GLIB_ST7920_128X64 u8g(18, 16, 17, U8G_PIN_NONE);                  // SPI Com: SCK = en = 18, MOSI = rw = 16, CS = di = 17

void flash() {
  if(leftHour<0){
    return ;
  }
  leftSecond--;
  if(leftSecond<0){
    leftSecond = 59;
    leftMinute--;
    if(leftMinute<0){
      leftMinute = 59;
      leftHour--;
      if(leftHour<0){
        isTimeOut = 1;      
      }
    }
  }
}
void IntegerToString(int a,char A[]){
  int index = 0;
  if(a==0){
    A[index++] = '0';
  }
  if(a<0){
    A[index++] = '-';
    a = -a;
  }
  while(a){
    A[index++] = a%10 + '0';
    a/=10;
  }
  A[index]='\0';
  int i = 0,j = index-1;
  if(A[0]=='-'){
    i=1;
  }
  char temp;
  for(;i<j;i++,j--){
    temp = A[i];
    A[i] = A[j];
    A[j] = temp;
  }
}
void timeout(){
    digitalWrite(controllPin, LOW);   // turn the LED on (HIGH is the voltage level)    
    delay(500);
    digitalWrite(controllPin, HIGH);   // turn the LED on (HIGH is the voltage level)    
}
void draw(){
    char Num[10];
    u8g.drawStr( 0, 0, "debug");
    u8g.drawStr( 0, 8, "hour:");
    u8g.drawStr( 0, 16, "minute:");
    u8g.drawStr( 0, 24, "second:");    
    IntegerToString(leftHour,Num);    
    u8g.drawStr( 40, 8, Num);
    IntegerToString(leftMinute,Num);    
    u8g.drawStr( 40, 16,Num);
    IntegerToString(leftSecond,Num);    
    u8g.drawStr( 40, 24,Num);    
}
void setup() {
  pinMode(controllPin, OUTPUT);
  digitalWrite(controllPin, HIGH);  
  Serial.begin(9600);
  
  MsTimer2::set(1000, flash); // 500ms period
  MsTimer2::start();
  u8g.setFont(u8g_font_6x10);
  u8g.setFontRefHeightExtendedText();
  u8g.setDefaultForegroundColor();
  u8g.setFontPosTop();
  
}
void loop() {
  char tempHour,tempMinute;
  if(Serial.available()>0){//some one send a message
    tempHour = Serial.read();
    tempMinute = Serial.read();
    Serial.write(tempHour);
    Serial.write(tempMinute);
    while(Serial.available()<=0);
    if(Serial.read()==123){
       leftHour = tempHour;
       leftMinute = tempMinute;
       leftSecond = 0;
    }    
  }
  u8g.firstPage();
  do{
    draw();
  }
  while(u8g.nextPage());  
  if(isTimeOut){
    timeout();
    isTimeOut = 0;
  }
}


